#coding=utf-8

import codecs
import urllib
import re
from BeautifulSoup import BeautifulSoup
import sys
reload(sys)
sys.setdefaultencoding('utf8')

class ctAnalytics():
	def __init__(self):
		pass
	'''
	分析课表
	'''
	def table_do(self,ct_html):
		soup = BeautifulSoup(ct_html, fromEncoding='utf-8')
		Table1 = soup.find("table", {"id": "Table1"}) #课表
		Table2 = soup.find("table", {"id": "Table2"}) #学生及课表相关信息
		Table3 = soup.find("table", {"id": "Table3"}) #其他课程信息
		'''
		寻找 学生及课表相关信息
		'''
		xn  = Table2.find("select", {"name": "xnd"}).find("option", {"selected": "selected"}).string
		xq  = Table2.find("select", {"name": "xqd"}).find("option", {"selected": "selected"}).string
		xh  = Table2.find("span", {"id": "Label5"}).string
		xm  = Table2.find("span", {"id": "Label6"}).string
		xy  = Table2.find("span", {"id": "Label7"}).string
		zy  = Table2.find("span", {"id": "Label8"}).string
		bj  = Table2.find("span", {"id": "Label9"}).string
		ct_info = {'xn':xn,'xq':xq,'xh':xh[3:],'xm':xm[3:],'xy':xy[3:],'zy':zy[3:],'bj':bj[4:]}
		'''
		寻找 课表信息
		'''
		Table1_tr = Table1.findAll("tr")
		ct_data = {} #定义课表字典
		row = 0
		for tr in Table1_tr: #循环课表每一行
			if row>1 and row%2==0: #只需要课表所在行（除0行以外的偶数行）
				y = row/2
				ct_data[y] = {}
				col = 0
				for td in tr.findAll("td"): #循环课表一行中的每一列
					x = 0
					if y%2==1 and col>1: #只需课表所在列（奇数行从第3列开始，偶数行从第二列开始）
						x = col-1
					if y%2==0 and col>0:
						x = col
					if x != 0:	
						ct_data[y][x] = self.table_tdAnalytics(td) #存储课表信息
					col += 1
			row += 1
		'''
		分析 table3
		'''
		ct_more = {}
		
		return {"ct_info":ct_info,"ct_data":ct_data,"ct_more":ct_more}
	'''
	分析课表html中td的内容
	'''
	def table_tdAnalytics(self,td):
		items = td.contents
		items_str = self.list2str(items)
		item_dict = {}
		class_i = 0
		for class_item in items_str.split("<br /><br />"):
			item_dict[class_i] = {}
			item_i = 0
			item_item_list = class_item.split("<br />")
			item_item_list_len = len(item_item_list)
			if item_item_list_len == 5 or item_item_list_len == 7:
				item_dict[class_i]["title"] = item_item_list[0]
				item_item_list_1 = re.split('{|节{第|周}|第|周|-|\n',item_item_list[2])
				item_dict[class_i]["week_d"] = item_item_list_1[1]
				item_dict[class_i]["class_n"] = item_item_list_1[2]
				item_dict[class_i]["week_s"] = item_item_list_1[3]
				item_dict[class_i]["week_e"] = item_item_list_1[4]
				item_dict[class_i]["teacher"] = item_item_list[3]
				item_dict[class_i]["addr"] = item_item_list[4]
			if item_item_list_len == 5:
				item_dict[class_i]["exam_time"] = ""
				item_dict[class_i]["exam_addr"] = ""
			if item_item_list_len == 7:
				item_dict[class_i]["exam_time"] = item_item_list[5]
				item_dict[class_i]["exam_addr"] = item_item_list[6]
			
			class_i += 1
		
		return item_dict
		
	def list2str(self,list):
		string = ""
		for item in list:
			string += str(item)
		return string

	def info_do(self,ct_html):
		soup = BeautifulSoup(ct_html, fromEncoding='utf-8')
		Table1 = soup.find("table") #
		'''
		寻找 个人信息
		'''
		Table1_tr = Table1.findAll("tr")
		ct_title = []
		ct_data  = []
		
		for tr in Table1_tr: #循环每一行
			col         = 1
			for td in tr.findAll("td"): #循环每一列
				if col < 7:
					span = td.findAll("span")
					if len(span) == 0:
						span_str = ""
					else:
						span_str = span[0].string
					
					if span_str == None:
						span_str = ""

					if col%2 == 0 and is_data:
						ct_data.append(span_str)
					else:
						if span_str != "":
							is_data = True
							ct_title.append(span_str)
						else:
							is_data = False
					col += 1

		return {'title':ct_title,'data':ct_data}

	def exam_do(self,ct_html):
		soup = BeautifulSoup(ct_html, fromEncoding='utf-8')
		Table1 = soup.find("table", {"id": "DataGrid1"}) #成绩
		'''
		寻找 考试信息
		'''
		Table1_tr = Table1.findAll("tr")
		ct_title = []
		ct_data  = []
		row      = 0
		for tr in Table1_tr: #循环每一行
			ct_row_data = []
			for td in tr.findAll("td"): #循环每一列
				if td.string == None:
					td.string = ""
				ct_row_data.append(td.string.strip("&nbsp;")) #存储信息

			if row == 0:
				ct_title = ct_row_data
			else:
				ct_data.append(ct_row_data)
			row += 1
		return {'title':ct_title,'data':ct_data}

	def score_do(self,ct_html):
		soup = BeautifulSoup(ct_html, fromEncoding='utf-8')
		Table1 = soup.find("table", {"id": "Datagrid1"}) #成绩
		'''
		寻找 成绩信息
		'''
		Table1_tr = Table1.findAll("tr")
		ct_title = []
		ct_data  = []
		row      = 0
		for tr in Table1_tr: #循环每一行
			ct_row_data = []
			for td in tr.findAll("td"): #循环每一列
				a = td.findAll("a")
				if len(a) == 1:
					td.string = a[0].string
				if td.string == None:
					td.string = ""
				ct_row_data.append(td.string.strip("&nbsp;")) #存储信息

			if row == 0:
				ct_title = ct_row_data
			else:
				ct_data.append(ct_row_data)
			row += 1
		return {'title':ct_title,'data':ct_data}